<template>
  <div v-if="visible" class="dialog-overlay">
    <div class="dialog">
      <!-- 头部 -->
      <div class="dialog-header">
        <h3>答题</h3>
        <button @click="handleClose">×</button>
      </div>
      
      <!-- 内容 -->
      <div class="dialog-body">
        <div v-if="loading">生成题目中...</div>
        <div v-else>
          <div v-for="(q, i) in quiz.questions" :key="i" class="question" :class="{ 'wrong-answer': showResults && !isAnswerCorrect(i) }">
            <h4>{{ i+1 }}. {{ q.header }}
              <button @click="logQuestion(q,i)" class="log-button">加入收藏</button>
            </h4>
            <div v-for="(choice, j) in q.choices" :key="j" class="choice">
              <input 
                type="radio" 
                :name="'q'+i" 
                :value="String.fromCharCode(65+j)"
                v-model="answers[i]"
                :disabled="showResults"
              >
              <label>{{ String.fromCharCode(65+j) }}. {{ choice }}</label>
            </div>
            <div v-if="showResults" class="answer-feedback">
              <div>你的答案: {{ answers[i] || '未作答' }}</div>
              <div>正确答案: {{ q.rightanswer }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 底部 -->
      <div class="dialog-footer">
        <button @click="handleSubmit" v-if="!showResults">提交</button>
        <button @click="handleClose" v-else>关闭</button>
      </div>
    </div>
    
    <!-- 关闭确认弹框 -->
    <div v-if="showCloseConfirm" class="confirm-dialog">
      <p>确定要关闭吗？未提交的答案将丢失</p>
      <button @click="confirmClose">确定</button>
      <button @click="showCloseConfirm = false">取消</button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { generateQuestions } from '@/api/modules/axiosApi'
import {Wchoixequestion } from '@/api/modules/axiosApi'
import { ElMessage } from 'element-plus'
import {insertmychoicequestion} from '@/api/modules/axiosApi'
import { useUserStore } from '@/stores/userStore'
// import questionclass from '../AI/StudentsExcise.vue'
const loggedQuestions = ref(new Set())
const props = defineProps({
  visible: Boolean,
  num: Number,
  questionclass: String,
  prompt: String
})

const emit = defineEmits(['update:visible', 'submit'])
let prompt=''
const quiz = ref(null)
const loading = ref(false)
const answers = ref([])
const showCloseConfirm = ref(false)
const showResults = ref(false)
//let  WcqQuestions={}
//let wrongAnswerschoice = [];
// 计算答错的题目
const wrongAnswers = computed(() => {
  if (!quiz.value || !showResults.value) return []
  
  return quiz.value.questions.map((q, i) => {
    const isCorrect = isAnswerCorrect(i)
    return !isCorrect ? {
      header: q.header,
      userAnswer: answers[i] || '未作答',
      correctAnswer: q.rightanswer,
      index: i,
      choices:q.choices
    } : null
  }).filter(Boolean)
})

// 检查单个答案是否正确
const isAnswerCorrect = (index) => {
  return answers.value[index] === quiz.value.questions[index].rightanswer
}

// 生成题目
watch(() => props.visible, async (visible) => {
  if (visible) {
    loading.value = true
    showResults.value = false
    try {
      const res = await generateQuestions(props.num, props.questionclass)
      quiz.value = res.data
      answers.value = new Array(props.num).fill(null)
      loggedQuestions.value.clear() // 每次打开对话框时清空记录
    } finally {
      loading.value = false
    }
  }
})

// 关闭处理
const handleClose = () => {
  if (answers.value.some(a => a !== null) && !showResults.value) {
    showCloseConfirm.value = true
  } else {
    emit('update:visible', false)
  }
}

const confirmClose = () => {
  showCloseConfirm.value = false
  emit('update:visible', false)
}
const logQuestion = (q,index) => {
  prompt=props.questionclass
  const userStore =  useUserStore() 
  let logchoice=[]
  let wcqQuestions={}
  q.choices.forEach((choice, j) => {
        logchoice.push(`${String.fromCharCode(65 + j)}. ${choice}`)
      })
      if (loggedQuestions.value.has(index)) {
     alert('这道题已经收藏过了，不能重复收藏！')
    return
  }
  console.log(JSON.stringify({
    header: q.header,
    answerschoice:logchoice,
    rightanswer: q.rightanswer
  }, null, 2));
  console.log(userStore.user.id);
  
  wcqQuestions.header=q.header
  wcqQuestions.answerschoice=logchoice
  wcqQuestions.rightanswer=q.rightanswer
  wcqQuestions.user_id=userStore.user.id
  wcqQuestions.prompt=prompt
  loggedQuestions.value.add(index); // 记录已经打印过的题目索引
  insertmychoicequestion(wcqQuestions)
  alert('收藏成功')
  console.log(prompt);
  console.log(wcqQuestions);
  
  
}

// 提交处理
const handleSubmit = async () => {
  prompt=props.questionclass
  const userStore =  useUserStore() 
  if (confirm('确定要提交答案吗？')) {
    showResults.value = true
     let allwrong=[]
    // console.log('========= 错题详情 =========')
   await wrongAnswers.value.forEach((wrong) => {
      // console.log(`题目: ${wrong.header}`)
      let answerschoice = [];
      let  WcqQuestions={}
      wrong.choices.forEach((choice, j) => {
        
        // console.log(`${String.fromCharCode(65 + j)}. ${choice}`)
        answerschoice.push(`${String.fromCharCode(65 + j)}. ${choice}`)
      })
      // console.log(`你的答案: ${wrong.userAnswer}`)
      // console.log(`正确答案: ${wrong.correctAnswer}`)
      // console.log(answerschoice);
      // console.log(`${wrong.header}`);
      // console.log(`${wrong.correctAnswer}`);
      
      // console.log('--------------------------')
       WcqQuestions.header=`${wrong.header}`
       WcqQuestions.answerschoice=answerschoice
       WcqQuestions.rightanswer=`${wrong.correctAnswer}`
       WcqQuestions.user_id=userStore.user.id
       WcqQuestions.prompt=prompt
      //  console.log(WcqQuestions);
       allwrong.push(WcqQuestions)
      
    })

    // console.log(`总共答错 ${wrongAnswers.value.length} 题`)
    //  console.log(allwrong);
    await Wchoixequestion(allwrong)
    emit('submit', { 
      quiz: quiz.value, 
      answers: answers.value,
      wrongAnswers: wrongAnswers.value
    })
  }
  console.log(prompt);
  
}

</script>

<style scoped>
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
   z-index: 9999; 
}

.dialog {
  background: white;
  width: 600px;
  max-width: 90%;
  max-height: 80vh;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.dialog-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.dialog-body {
  padding: 16px;
  overflow-y: auto;
  flex-grow: 1;
}

.question {
  margin-bottom: 20px;
  padding: 10px;
  border-radius: 4px;
}

.wrong-answer {
  background-color: #ffeeee;
  border-left: 3px solid #ff5252;
}

.choice {
  margin: 8px 0;
  display: flex;
  align-items: center;
}

.answer-feedback {
  margin-top: 10px;
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.dialog-footer {
  padding: 16px;
  border-top: 1px solid #eee;
  text-align: right;
}

.confirm-dialog {
  position: fixed;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.2);
}
</style>